package cn.fl.warrant.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.fl.warrant.service.IArcDayMaintainService;
import cn.fl.warrant.service.IArcMgrMainService;
import cn.fl.warrant.transform.ArcDayMaintainVOTransform;
import cn.fl.warrant.vo.ArcDayMaintainVO;
import cn.fl.capital.vo.CapPayListRepVO;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysOrgService;
import cn.fl.system.vo.SysOrgVO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.warrant.facade.archive.condition.ArcDayMaintainQueryCondition;
import fl.warrant.facade.archive.constant.ArchiveConstants;

/**
 * @Description: 归档天数维护 控制层
 */
@Controller
@RequestMapping("/archive/arcDayMaintain")
public class ArcDayMaintainController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcDayMaintainController.class);

	@Autowired
	private IArcMgrMainService arcMgrMainService;
	@Autowired
	private IArcDayMaintainService  arcDayMaintainService;
	/**
	 * 客户 服务层BEAN
	 */
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private ISysOrgService sysOrgService;

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcDayMaintain/arcDayMaintainList");
		 //事业部
  		List<KeyValueVO> orgList = this.cstBscInfoService
  						.searchBusinessOrgList();
  		request.setAttribute("buOrgCdList", orgList);
  		//省公司
  		request.setAttribute("prList", arcMgrMainService.getPrList());
				
		BaseLogUtils.info(logger, "toListPage", "跳转到归档天数列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增页面
	 */
	@RequestMapping(value = "/toAddPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toAddPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");
		String flag = request.getParameter("flag");
		ModelAndView view = new ModelAndView("archive/arcDayMaintain/arcDayMaintainSave");
		 //事业部
  		List<KeyValueVO> orgList = this.cstBscInfoService
  						.searchBusinessOrgList();
  		request.setAttribute("buOrgCdList", orgList);
  		//省公司
  		request.setAttribute("prList", arcMgrMainService.getPrList());
        if(id != null){
			//获取信息
			ArcDayMaintainVO entity = null;
			try {
				entity = this.arcDayMaintainService.selectById(Long.valueOf(id));
			} catch (Exception e) {
				BaseLogUtils.error(logger, "toAddPage", "获取归档基础信息错误!" + e.getMessage());
			}
			if(null != entity){
				view.addObject("arcDay", entity.getArcDay());
				view.addObject("bussDepartment", entity.getBussDepartment());
				view.addObject("proCompany", entity.getProCompany());
			}else{
				view.addObject("arcDay", "");
				view.addObject("bussDepartment", "");
				view.addObject("proCompany", "");
			}
			view.addObject("id", id);//修改时使用的关联关系ID
			view.addObject("flag", flag);
        }
		BaseLogUtils.info(logger, "toModifyPage", "跳转到修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String beginPigeonholeDays = request.getParameter("beginPigeonholeDays");
		String endPigeonholeDays = request.getParameter("endPigeonholeDays");
		String bussDepartment  = request.getParameter("bussDepartment");
		String proCompany  = request.getParameter("proCompany");//cstMgrOrgCd
//		if(proCompany.length()>12){//保留到省公司
//			proCompany=proCompany.substring(0,12);
//		}
		Pager page = new Pager();
		ArcDayMaintainQueryCondition qc= new ArcDayMaintainQueryCondition();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}
		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}
		 qc = new ArcDayMaintainQueryCondition();
		if (StringUtils.isNotEmpty(bussDepartment)) {
			qc.setBussDepartment(bussDepartment);
		}
		if (StringUtils.isNotEmpty(proCompany)) {
			qc.setProCompany(proCompany);
		}
		if (StringUtils.isNotEmpty(endPigeonholeDays)) {
			qc.setEndPigeonholeDays(endPigeonholeDays);
		}
		if (StringUtils.isNotEmpty(beginPigeonholeDays)) {
			qc.setBeginPigeonholeDays(beginPigeonholeDays);
		}
        page.setCondition(qc);
        //事业部
  		List<KeyValueVO> orgList = this.cstBscInfoService
  						.searchBusinessOrgList();
  		request.setAttribute("buOrgCdList", orgList);
  		//省公司
  		request.setAttribute("prList", arcMgrMainService.getPrList());
		Pager pager = this.arcDayMaintainService.searchListPage(page);
		BaseLogUtils.info(logger, "initarcDayMaintainList", "初始化列表arcDayMaintainList页面数据.DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		List<ArcDayMaintainVO> list = (List<ArcDayMaintainVO>) pager.getResultList();
		ListPageVO<ArcDayMaintainVO> listPage = new ListPageVO<ArcDayMaintainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcDayMaintainService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			ArcDayMaintainVO vo = this.arcDayMaintainService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增保存
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(ArcDayMaintainVO entity,String json,HttpServletRequest request) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		int flag=0;
		String oldproCompany = request.getParameter("oldproCompany");
		String  oldbussDepartment = request.getParameter("oldbussDepartment");
		try {
//			if(entity.getProCompany().length()>12){
//				entity.setProCompany(entity.getProCompany().substring(0,12));//组织树省公司赋值给下拉型省公司
//			}
			if(entity.getId() == null) {//新增
				entity.setIsValid(ArchiveConstants.IS_VALID);
				entity.setIsDel(ArchiveConstants.IS_DEL);
				entity.setCrtTm(new Date());
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				//判断  同一省公司事业部不允许有两条
				flag = arcDayMaintainService.selectOne(entity);
				if(flag > 0){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("同一省公司事业部不允许重复添加!");
					System.out.println("同一省公司事业部不允许重复添加");
					BaseLogUtils.error(logger, "add", "保存数据失败.DATA:同一省公司事业部不允许重复添加" , CurrentThreadContext.getCurrentUserName());
					return result;
				}else{
					Long id = arcDayMaintainService.add(entity);
					result.setData(id);
				}
			}else {//修改
//				修改省公司判空
				if(entity.getProCompany() == null || "".equals(entity.getProCompany().toString())){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("修改时数据加载完成在点击保存!");
					System.out.println("修改时数据加载完成在点击保存!");
					BaseLogUtils.error(logger, "modify", "保存数据失败.DATA:修改时数据加载完成在点击保存!" , CurrentThreadContext.getCurrentUserName());
					return result;
				}else{
					//判断  同一省公司事业部不允许有两条
					if(oldbussDepartment.equals(entity.getBussDepartment().toString()) && oldproCompany.equals(entity.getProCompany().toString())){
					}else{
						flag = arcDayMaintainService.selectOne(entity);
					}
				}
				if(flag > 0){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("同一省公司事业部不允许重复添加!");
					System.out.println("同一省公司事业部不允许重复添加");
					BaseLogUtils.error(logger, "modify", "保存数据失败.DATA:同一省公司事业部不允许重复添加" , CurrentThreadContext.getCurrentUserName());
					return result;
				}else{
					entity.setIsValid(ArchiveConstants.IS_VALID);
					entity.setIsDel(ArchiveConstants.IS_DEL);
					entity.setMdfTm(new Date());
					entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					this.arcDayMaintainService.modify(entity);
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
				}
			}
			BaseLogUtils.info(logger, "save", "操作数据. DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "保存数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "保存数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		ArcDayMaintainVO entity = null;
		try {
			entity = new ArcDayMaintainVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.arcDayMaintainService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
    
}

